package org.ch02.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * 实例化任意类型的对象
 *
 * @author ZJL
 * @date 2025-03-17
 */
public class BeanUtil {
    /**
     * 创建任意对象
     *
     * @param className
     * @return
     */
    public static Object createBean(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            Constructor<?> constructor = clazz.getConstructor();
            return constructor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void invokeMethod(String className, String methodName, Class<?>[] parameterTypes, Object... params) {
        try {
            Class<?> clazz = Class.forName(className);
            Method method = clazz.getMethod(methodName, parameterTypes);
            method.invoke(createBean(className), params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
